/*
 * hkh-project
 * leafteamwork.blogspot.com
 * Tool: Netbeans 6.7.1 - SQL Server 2005
 */
package vn.com.hkh.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vn.com.hkh.dto.RoomDTO;
import vn.com.hkh.dto.UserDTO;
import vn.com.hkh.service.RoomService;
import vn.com.hkh.util.DatabaseUtil;

/**
 *
 * @author leaf
 */
public class RoomAction extends HttpServlet {

     private RoomService rs = null;

    @Override
    public void init() throws ServletException {
        super.init();
        rs = new RoomService();
    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        String forward = "";


        PrintWriter out = response.getWriter();
        try {
            String _message = "";
            if (request.getSession().getAttribute("login") == null) {
                _message = "Please login!";
                request.setAttribute("message", _message);
                RequestDispatcher rd = request.getRequestDispatcher("/LoginAction");
                rd.forward(request, response);
            } else {
                // T01. CLIENT PROCESS
                String action = request.getParameter("act");
                action = (action == null) ? "list" : action;

                // T02. CRUD PROCESS
                if (action.equalsIgnoreCase("add")) {
                    RoomDTO _roomDTO = new RoomDTO();
                    //TODO: *** Add Room task
                    //request from room add

                    _roomDTO.setId(DatabaseUtil.generateUUID());

                    _roomDTO.setName(request.getParameter("name"));
                    _roomDTO.setImage(request.getParameter("image"));
                    _roomDTO.setContent(request.getParameter("content"));
                    _roomDTO.setAlias(request.getParameter("alias"));
                    _roomDTO.setPrice(request.getParameter("price"));
                    _roomDTO.setPosition(Integer.parseInt(request.getParameter("position")));
                    _roomDTO.setStatus(Integer.parseInt(request.getParameter("status")));
                    _roomDTO.setWhen(request.getParameter("when"));

                    UserDTO _userDTO = (UserDTO) request.getSession().getAttribute("login");
                    _roomDTO.setUser(_userDTO);

                    RoomDTO _result = rs.create(_roomDTO);
                    if (_result == null) {
                        _message = "Add Error!";
                        request.setAttribute("room", _roomDTO);
                        action = "addform";
                    } else {
                        _message = "Add Successful!";
                        action = "list";
                    }
                } else if (action.equalsIgnoreCase("edit")) {
                    RoomDTO _roomDTO = new RoomDTO();
                    //TODO: *** Add Room task
                    //request from room edit
                    _roomDTO.setId(request.getParameter("id"));
                    _roomDTO.setName(request.getParameter("name"));
                    _roomDTO.setImage(request.getParameter("image"));
                    _roomDTO.setContent(request.getParameter("content"));
                    _roomDTO.setAlias(request.getParameter("alias"));
                    _roomDTO.setPrice(request.getParameter("price"));
                    _roomDTO.setPosition(Integer.parseInt(request.getParameter("position")));
                    _roomDTO.setStatus(Integer.parseInt(request.getParameter("status")));
                    _roomDTO.setWhen(request.getParameter("when"));

                    UserDTO _userDTO = (UserDTO) request.getSession().getAttribute("login");
                    _roomDTO.setUser(_userDTO);

                    RoomDTO _result = rs.store(_roomDTO);
                    if (_result == null) {
                        _message = "Update Error!";
                        request.setAttribute("room", _roomDTO);
                        action = "editform";
                    } else {
                        _message = "Update Successful!";
                        action = "list";
                    }
                } else if (action.equalsIgnoreCase("del")) {
                    String primaryKey = request.getParameter("pk");
                    boolean result = rs.remove(primaryKey);
                    _message = result ? "Delete Successful!" : "Delete Error!";
                    action = "list";
                } else if (action.equalsIgnoreCase("cancel")) {
                    _message = null;
                    action = "list";
                }

                // T03. FORWARD PROCESS
                if (action.equalsIgnoreCase("list")) {
                    Collection<RoomDTO> _roomDTO = rs.findRooms();
                    request.setAttribute("rooms", _roomDTO);
                    forward = (_roomDTO == null) ? "" : "/view/roomlist.jsp";
                } else if (action.equalsIgnoreCase("addform")) {
                    forward = "/view/roomadd.jsp";
                } else if (action.equalsIgnoreCase("editform")) {
                    RoomDTO _roomDTO = (RoomDTO) request.getAttribute("room");
                    if (_roomDTO == null) {
                        String _roomID = request.getParameter("pk");
                        _roomDTO = rs.findByPrimaryKey(_roomID);
                        _roomDTO.setWhen(DatabaseUtil.getYMD(_roomDTO.getWhen()));
                        request.setAttribute("room", _roomDTO);
                    }
                    forward = (_roomDTO == null) ? "" : "/view/roomedit.jsp";
                }

                //T04. LOOKUP & FORWARD TO VIEW
                request.setAttribute("from", "roomaction");
                request.setAttribute("message", _message);
                request.setAttribute("forward", forward);
                RequestDispatcher rd = request.getRequestDispatcher("/view/adminlayout.jsp");
                rd.forward(request, response);
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    @Override
    public void destroy() {
        super.destroy();
        rs = null;
    }
}
